package cn.com.css.taxInspection.system.service;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import cn.com.css.taxInspection.common.exception.BusinessException;
import cn.com.css.taxInspection.common.exception.code.BaseResponseCode;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;


/**
 * redis
 */
@Service
public class RedisService {

    @Value("${spring.redisToken.key.prefix.userToken}")
    private String userTokenPrefix;

    private final StringRedisTemplate redisTemplate;

    public RedisService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public boolean exists(String key) {
        return this.redisTemplate.hasKey(key);
    }

    public Long getExpire(String key) throws BusinessException {
        if (null == key) {
            throw new BusinessException(BaseResponseCode.DATA_ERROR.getCode(), "key or TomeUnit 不能为空");
        }
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }


    public void set(String key, String value) {
        this.redisTemplate.opsForValue().set(key, value);
    }


    public String get(String key) {
        return this.redisTemplate.opsForValue().get(key);
    }

    public void del(String key) {
        if (this.exists(key)) {
            this.redisTemplate.delete(key);
        }

    }

    public void setAndExpire(String key, String value, long seconds) {
        this.redisTemplate.opsForValue().set(key, value);
        this.redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    }


    public Set<String> keys(String pattern) {
        return redisTemplate.keys("*" + pattern);
    }

    public void delKeys(String pattern) {
        Set<String> keys = redisTemplate.keys(pattern);
        if (!CollectionUtils.isEmpty(keys)) {
            this.redisTemplate.delete(keys);
        }
    }

    public Map<String, Object> getUserDataFromRedis(String accessToken) {
        String redisKey = userTokenPrefix + accessToken;

        // 从 Redis 读取字符串
        String jsonData = redisTemplate.opsForValue().get(redisKey);
        if (jsonData == null || jsonData.isEmpty()) {
            throw new BusinessException(BaseResponseCode.TOKEN_ERROR);
        }

        try {
            // 转换 JSON -> Map<String, Object>
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(jsonData, new TypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            throw new RuntimeException("解析 Redis 中的 Token 数据失败", e);
        }
    }


}
